import { invoke } from '@tauri-apps/api/core';
import { listen } from '@tauri-apps/api/event';
import {
  CtpAccountConfig,
  ApiResponse,
  MarketDataRequest,
  OrderRequest,
  ConnectionStatus,
  LogEntry,
  LogLevel,
  MarketDataInfo,
  AccountInfo,
  PositionInfo,
  InstrumentInfo
} from '../types/ctp';
import { sessionManager } from './sessionManager';
// import { cacheManager } from './cacheManager'; // 临时屏蔽缓存管理器

// 检查是否在 Tauri 环境中 - 使用 Tauri 2.0 推荐的检测方式
async function isTauriEnvironment(): Promise<boolean> {
  try {
    // Tauri 2.0 推荐的检测方式：尝试导入 Tauri API
    const { invoke } = await import('@tauri-apps/api/core');

    // 如果能成功导入并调用，说明在 Tauri 环境中
    await invoke('get_api_version'); // 测试调用一个已知的命令
    return true;
  } catch (error) {
    // 如果导入失败或调用失败，可能不在 Tauri 环境中
    return false;
  }
}

// 安全的 invoke 函数
async function safeInvoke(command: string, args?: any): Promise<any> {
  const isTauri = await isTauriEnvironment();
  if (!isTauri) {
    throw new Error('Not running in Tauri environment. Please run the application through Tauri.');
  }

  try {
    return await invoke(command, args);
  } catch (error) {
    throw error;
  }
}

export class CtpService {
  private static instance: CtpService | null = null;
  private mdSessionId: string | null = null;
  private traderSessionId: string | null = null;
  private mdStatus: ConnectionStatus = 'disconnected' as ConnectionStatus;
  private traderStatus: ConnectionStatus = 'disconnected' as ConnectionStatus;
  private logs: LogEntry[] = [];
  private eventListeners: Map<string, Function[]> = new Map();
  // 窗口级别的事件监听器 - 格式: eventType -> windowId -> Function[]
  private windowEventListeners: Map<string, Map<string, Function[]>> = new Map();

  private constructor() {
    this.initEventListeners();
    this.loadSessionFromCache();
    this.initTauriEventListeners();
  }

  // 获取单例实例
  public static getInstance(): CtpService {
    if (!CtpService.instance) {
      CtpService.instance = new CtpService();
    }
    return CtpService.instance;
  }

  // 从缓存加载会话信息
  private loadSessionFromCache(): void {
    const sessionInfo = sessionManager.getSessionInfo();
    if (sessionInfo) {
      this.mdSessionId = sessionInfo.mdSessionId;
      this.traderSessionId = sessionInfo.traderSessionId;
      this.mdStatus = sessionInfo.mdStatus as ConnectionStatus;
      this.traderStatus = sessionInfo.traderStatus as ConnectionStatus;
    }
  }

  // 保存会话信息到缓存
  private saveSessionToCache(): void {
    sessionManager.saveSessionInfo({
      mdSessionId: this.mdSessionId,
      traderSessionId: this.traderSessionId,
      mdStatus: this.mdStatus,
      traderStatus: this.traderStatus,
      lastUpdateTime: new Date().toISOString()
    });
  }

  // 获取安全的流文件路径
  private getFlowPath(type: 'md' | 'trader', sessionId: string): string {
    // 使用系统临时目录，避免影响项目文件监听
    // 在 Windows 上通常是 %TEMP%，在 Linux/Mac 上是 /tmp
    return `../temp/ctp_cache/${type}_${sessionId}`;
  }

  private initEventListeners() {
    // 初始化事件监听器
    this.eventListeners.set('md_status_change', []);
    this.eventListeners.set('trader_status_change', []);
    this.eventListeners.set('market_data', []);
    this.eventListeners.set('order_update', []);
    this.eventListeners.set('trade_update', []);
    this.eventListeners.set('log', []);

    // 初始化窗口级别的事件监听器
    this.windowEventListeners.set('market_data', new Map());
    this.windowEventListeners.set('md_status_change', new Map());
    this.windowEventListeners.set('trader_status_change', new Map());
    this.windowEventListeners.set('order_update', new Map());
    this.windowEventListeners.set('trade_update', new Map());
  }

  private async initTauriEventListeners() {
    try {
      // 监听来自Tauri后端的market_data事件
      await listen('market_data', (event) => {
        const marketData = event.payload as MarketDataInfo;

        // 转发到内部事件系统（保持向后兼容）
        this.emit('market_data', marketData);

        // 向所有窗口广播行情数据
        this.emitToAllWindows('market_data', marketData);

        // 添加日志
        this.addLog(`收到行情数据: ${marketData.instrument_id}, 价格=${marketData.last_price}`, LogLevel.Info);
      });

      // 监听来自Tauri后端的order_update事件
      await listen('order_update', (event) => {
        const orderUpdate = event.payload as any;

        // 转发到内部事件系统
        this.emit('order_update', orderUpdate);

        // 向所有窗口广播订单更新
        this.emitToAllWindows('order_update', orderUpdate);

        // 添加日志
        this.addLog(`收到订单更新: ${JSON.stringify(orderUpdate)}`, LogLevel.Info);
      });

      // 监听来自Tauri后端的trade_update事件
      await listen('trade_update', (event) => {
        const tradeUpdate = event.payload as any;

        // 转发到内部事件系统
        this.emit('trade_update', tradeUpdate);

        // 向所有窗口广播成交更新
        this.emitToAllWindows('trade_update', tradeUpdate);

        // 添加日志
        this.addLog(`收到成交更新: ${JSON.stringify(tradeUpdate)}`, LogLevel.Info);
      });
    } catch (error) {
      this.addLog(`初始化Tauri事件监听失败: ${error}`, LogLevel.Error);
    }
  }

  // 事件管理
  on(event: string, callback: Function) {
    if (!this.eventListeners.has(event)) {
      this.eventListeners.set(event, []);
    }
    this.eventListeners.get(event)!.push(callback);
  }

  off(event: string, callback: Function) {
    const listeners = this.eventListeners.get(event);
    if (listeners) {
      const index = listeners.indexOf(callback);
      if (index > -1) {
        listeners.splice(index, 1);
      }
    }
  }

  // 窗口级别的事件管理
  onWindow(event: string, windowId: string, callback: Function) {
    if (!this.windowEventListeners.has(event)) {
      this.windowEventListeners.set(event, new Map());
    }

    const eventMap = this.windowEventListeners.get(event)!;
    if (!eventMap.has(windowId)) {
      eventMap.set(windowId, []);
    }

    eventMap.get(windowId)!.push(callback);
  }

  offWindow(event: string, windowId: string, callback?: Function) {
    const eventMap = this.windowEventListeners.get(event);
    if (!eventMap) return;

    const listeners = eventMap.get(windowId);
    if (!listeners) return;

    if (callback) {
      // 移除特定的回调函数
      const index = listeners.indexOf(callback);
      if (index > -1) {
        listeners.splice(index, 1);
      }
    } else {
      // 移除该窗口的所有监听器
      eventMap.delete(windowId);
    }
  }

  private emit(event: string, data?: any) {
    const listeners = this.eventListeners.get(event);
    if (listeners) {
      listeners.forEach(callback => callback(data));
    }
  }

  // 向特定窗口发送事件
  private emitToWindow(event: string, windowId: string, data?: any) {
    const eventMap = this.windowEventListeners.get(event);
    if (!eventMap) return;

    const listeners = eventMap.get(windowId);
    if (listeners) {
      listeners.forEach(callback => callback(data));
    }
  }

  // 向所有窗口广播事件
  private emitToAllWindows(event: string, data?: any) {
    const eventMap = this.windowEventListeners.get(event);
    if (!eventMap) return;

    eventMap.forEach((listeners, windowId) => {
      listeners.forEach(callback => callback(data));
    });
  }

  private addLog(message: string, level: LogLevel = LogLevel.Info, data?: any) {
    const logEntry: LogEntry = {
      timestamp: new Date().toISOString(),
      level,
      message,
      data
    };
    this.logs.unshift(logEntry);
    if (this.logs.length > 1000) {
      this.logs.pop();
    }
    this.emit('log', logEntry);
  }

  // 基础 API 方法
  async getApiVersion(): Promise<ApiResponse<string>> {
    try {
      const result = await safeInvoke('get_api_version') as ApiResponse<string>;
      this.addLog(`获取API版本: ${result.success ? '成功' : '失败'}`, 
        result.success ? LogLevel.Info : LogLevel.Error, result);
      return result;
    } catch (error) {
      this.addLog(`获取API版本异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 行情 API 方法
  async createMdApi(flowPath?: string): Promise<ApiResponse<string>> {
    try {
      const sessionId = `md_${Date.now()}`;
      const safePath = flowPath || this.getFlowPath('md', sessionId);

      this.addLog(`创建行情API，流文件路径: ${safePath}`, LogLevel.Info);

      const result = await safeInvoke('create_md_api', {
        sessionId,
        flowPath: safePath,
        isUsingUdp: false,
        isMulticast: false
      }) as ApiResponse<string>;

      if (result.success) {
        this.mdSessionId = sessionId;
        this.mdStatus = 'connected' as ConnectionStatus;
        this.emit('md_status_change', this.mdStatus);
        this.addLog(`创建行情API成功: ${sessionId}`, LogLevel.Info);
        this.saveSessionToCache(); // 保存会话信息
      } else {
        this.addLog(`创建行情API失败: ${result.error}`, LogLevel.Error, result);
      }
      return result;
    } catch (error) {
      this.addLog(`创建行情API异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async releaseMdApi(): Promise<ApiResponse<string>> {
    if (!this.mdSessionId) {
      const error = '没有活跃的行情API会话';
      this.addLog(error, LogLevel.Warning);
      return { success: false, error };
    }

    try {
      this.addLog(`释放行情API: ${this.mdSessionId}`, LogLevel.Info);

      const result = await safeInvoke('release_md_api', {
        sessionId: this.mdSessionId
      }) as ApiResponse<string>;

      if (result.success) {
        this.addLog(`行情API释放成功: ${this.mdSessionId}`, LogLevel.Info);
        this.mdSessionId = null;
        this.mdStatus = 'disconnected' as ConnectionStatus;
        this.emit('md_status_change', this.mdStatus);
      } else {
        this.addLog(`行情API释放失败: ${result.error}`, LogLevel.Error, result);
      }
      return result;
    } catch (error) {
      this.addLog(`释放行情API异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async mdLogin(config: CtpAccountConfig): Promise<ApiResponse<string>> {
    if (!this.mdSessionId) {
      const error = '请先创建行情API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      this.mdStatus = 'connecting' as ConnectionStatus;
      this.emit('md_status_change', this.mdStatus);

      this.addLog(`开始行情登录: ${config.md_front}`, LogLevel.Info);

      const result = await safeInvoke('md_login', {
        sessionId: this.mdSessionId,
        config
      }) as ApiResponse<string>;

      if (result.success) {
        // 注意：MD登录是异步过程，这里只是启动了登录流程
        // 实际的登录状态需要通过回调来确认
        this.mdStatus = 'login_success' as ConnectionStatus;
        this.addLog('行情登录流程已启动', LogLevel.Info);
        this.addLog(`登录信息: ${result.data}`, LogLevel.Info);

        // 给一些时间让连接建立
        await new Promise(resolve => setTimeout(resolve, 2000));

      } else {
        this.mdStatus = 'login_failed' as ConnectionStatus;
        this.addLog(`行情登录失败: ${result.error}`, LogLevel.Error, result);
      }

      this.emit('md_status_change', this.mdStatus);
      return result;
    } catch (error) {
      this.mdStatus = 'error' as ConnectionStatus;
      this.emit('md_status_change', this.mdStatus);
      this.addLog(`行情登录异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async subscribeMarketData(instrumentIds: string[]): Promise<ApiResponse<string>> {
    if (!this.mdSessionId) {
      const error = '请先创建行情API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      const request: MarketDataRequest = { instrument_ids: instrumentIds };
      const result = await safeInvoke('subscribe_market_data', {
        sessionId: this.mdSessionId,
        request
      }) as ApiResponse<string>;

      if (result.success) {
        this.addLog(`订阅行情成功: ${instrumentIds.join(', ')}`, LogLevel.Info);
      } else {
        this.addLog(`订阅行情失败: ${result.error}`, LogLevel.Error, result);
      }
      return result;
    } catch (error) {
      this.addLog(`订阅行情异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async unsubscribeMarketData(instrumentIds: string[]): Promise<ApiResponse<string>> {
    if (!this.mdSessionId) {
      const error = '请先创建行情API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      const request: MarketDataRequest = { instrument_ids: instrumentIds };
      const result = await safeInvoke('unsubscribe_market_data', {
        sessionId: this.mdSessionId,
        request
      }) as ApiResponse<string>;

      if (result.success) {
        this.addLog(`取消订阅成功: ${instrumentIds.join(', ')}`, LogLevel.Info);
      } else {
        this.addLog(`取消订阅失败: ${result.error}`, LogLevel.Error, result);
      }
      return result;
    } catch (error) {
      this.addLog(`取消订阅异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 交易 API 方法
  async createTraderApi(flowPath?: string): Promise<ApiResponse<string>> {
    try {
      const sessionId = `trader_${Date.now()}`;
      const safePath = flowPath || this.getFlowPath('trader', sessionId);

      this.addLog(`创建交易API，流文件路径: ${safePath}`, LogLevel.Info);

      const result = await safeInvoke('create_trader_api', {
        sessionId,
        flowPath: safePath,
        encrypt: false
      }) as ApiResponse<string>;

      if (result.success) {
        this.traderSessionId = sessionId;
        this.traderStatus = 'connected' as ConnectionStatus;
        this.emit('trader_status_change', this.traderStatus);
        this.addLog(`创建交易API成功: ${sessionId}`, LogLevel.Info);
        this.saveSessionToCache(); // 保存会话信息
      } else {
        this.addLog(`创建交易API失败: ${result.error}`, LogLevel.Error, result);
      }
      return result;
    } catch (error) {
      this.addLog(`创建交易API异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async traderLogin(config: CtpAccountConfig): Promise<ApiResponse<string>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      this.traderStatus = 'connecting' as ConnectionStatus;
      this.emit('trader_status_change', this.traderStatus);

      const result = await safeInvoke('trader_login', {
        sessionId: this.traderSessionId,
        config
      }) as ApiResponse<string>;

      if (result.success) {
        this.traderStatus = 'login_success' as ConnectionStatus;
        this.addLog('交易登录成功', LogLevel.Info);
        this.saveSessionToCache(); // 保存会话信息
      } else {
        this.traderStatus = 'login_failed' as ConnectionStatus;
        this.addLog(`交易登录失败: ${result.error}`, LogLevel.Error, result);
      }
      
      this.emit('trader_status_change', this.traderStatus);
      return result;
    } catch (error) {
      this.traderStatus = 'error' as ConnectionStatus;
      this.emit('trader_status_change', this.traderStatus);
      this.addLog(`交易登录异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async insertOrder(order: OrderRequest, windowContext?: { windowId?: string, contractCode?: string }): Promise<ApiResponse<string>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      // 添加窗口上下文信息到请求中
      const requestWithContext = {
        sessionId: this.traderSessionId,
        order,
        windowContext: windowContext || {}
      };

      const result = await safeInvoke('insert_order', requestWithContext) as ApiResponse<string>;

      if (result.success) {
        this.addLog(`下单成功: ${order.instrument_id} ${order.direction === '0' ? '买入' : '卖出'} ${order.volume}手 @${order.price}`, LogLevel.Info);
      } else {
        this.addLog(`下单失败: ${result.error}`, LogLevel.Error, result);
        // 播放错误提示音
        await safeInvoke('play_error_sound');
      }
      return result;
    } catch (error) {
      this.addLog(`下单异常: ${error}`, LogLevel.Error, error);
      // 播放错误提示音
      try {
        await safeInvoke('play_error_sound');
      } catch (audioError) {
        // 忽略音频播放错误
      }
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async cancelOrder(orderRef: string, instrumentId?: string, windowContext?: { windowId?: string, contractCode?: string }): Promise<ApiResponse<any>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      // 验证合约代码
      if (!instrumentId) {
        const error = '撤单失败：合约代码不能为空';
        this.addLog(error, LogLevel.Error);
        return { success: false, error };
      }

      // 构造撤单请求对象
      const cancelRequest = {
        instrument_id: instrumentId,
        order_ref: orderRef,
        front_id: null,  // CTP会自动填充
        session_id: null, // CTP会自动填充
        exchange_id: "SHFE", // 上海期货交易所
        order_sys_id: null // 系统订单编号（可选）
      };

      // 第一步：提交撤单请求，添加窗口上下文信息
      const submitResult = await safeInvoke('cancel_order', {
        sessionId: this.traderSessionId,
        cancelRequest,
        windowContext: windowContext || {}
      }) as ApiResponse<string>;

      if (!submitResult.success) {
        this.addLog(`撤单提交失败: ${submitResult.error}`, LogLevel.Error, submitResult);
        return submitResult;
      }

      // 第二步：等待撤单结果
      const actionRef = submitResult.data; // 这是action_ref
      this.addLog(`撤单请求已提交，等待结果... ActionRef: ${actionRef}`, LogLevel.Info);

      const resultResponse = await safeInvoke('get_cancel_order_result', {
        actionRef
      }) as ApiResponse<any>;

      if (resultResponse.success && resultResponse.data) {
        const cancelResult = resultResponse.data;
        if (cancelResult.success) {
          this.addLog(`撤单成功: 订单${cancelResult.order_ref}`, LogLevel.Info);
          return {
            success: true,
            data: {
              message: `撤单成功: 订单${cancelResult.order_ref}`,
              orderRef: cancelResult.order_ref,
              actionRef: cancelResult.action_ref,
              status: cancelResult.status
            }
          };
        } else {
          this.addLog(`撤单失败: ${cancelResult.message}`, LogLevel.Error, cancelResult);
          return {
            success: false,
            error: cancelResult.message,
            data: cancelResult
          };
        }
      } else {
        this.addLog(`撤单结果查询失败: ${resultResponse.error}`, LogLevel.Error, resultResponse);
        return {
          success: false,
          error: resultResponse.error || '撤单结果查询失败',
          data: resultResponse.data
        };
      }
    } catch (error) {
      this.addLog(`撤单异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 撤单操作（完整参数版本）
  async cancelOrderWithRequest(cancelRequest: any, windowContext?: { windowId?: string, contractCode?: string }): Promise<ApiResponse<string>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      this.addLog(`撤单请求: ${JSON.stringify(cancelRequest)}`, LogLevel.Info);

      const result = await safeInvoke('cancel_order', {
        sessionId: this.traderSessionId,
        cancelRequest,
        windowContext: windowContext || {}
      }) as ApiResponse<string>;

      if (result.success) {
        this.addLog(`撤单成功: ${result.data}`, LogLevel.Info);
      } else {
        this.addLog(`撤单失败: ${result.error}`, LogLevel.Error);
      }

      return result;
    } catch (error) {
      this.addLog(`撤单异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 查询账户资金
  async queryAccount(): Promise<ApiResponse<AccountInfo>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    if (this.traderStatus !== 'login_success') {
      const error = '交易API未登录';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      this.addLog('查询账户资金信息', LogLevel.Info);

      const result = await safeInvoke('query_account', {
        sessionId: this.traderSessionId
      }) as ApiResponse<AccountInfo>;

      if (result.success) {
        this.addLog('账户资金查询成功', LogLevel.Info);
        this.addLog(`可用资金: ${result.data?.available || 0}`, LogLevel.Info);
      } else {
        this.addLog(`账户资金查询失败: ${result.error}`, LogLevel.Error, result);
      }

      return result;
    } catch (error) {
      this.addLog(`账户资金查询异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 查询持仓信息
  async queryPosition(): Promise<ApiResponse<PositionInfo[]>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    if (this.traderStatus !== 'login_success') {
      const error = '交易API未登录';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      this.addLog('查询持仓信息', LogLevel.Info);

      const result = await safeInvoke('query_position', {
        sessionId: this.traderSessionId
      }) as ApiResponse<PositionInfo[]>;

      if (result.success) {
        const positions = result.data || [];
        this.addLog(`持仓查询成功，共 ${positions.length} 个持仓`, LogLevel.Info);

        // 记录主要持仓信息
        positions.forEach(pos => {
          this.addLog(`持仓: ${pos.instrument_id} ${pos.posi_direction === '2' ? '多' : '空'} ${pos.position}手`, LogLevel.Info);
        });
      } else {
        this.addLog(`持仓查询失败: ${result.error}`, LogLevel.Error, result);
      }

      return result;
    } catch (error) {
      this.addLog(`持仓查询异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 查询所有订单
  async queryAllOrders(): Promise<ApiResponse<any[]>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      this.addLog('查询账号下所有订单', LogLevel.Info);

      const result = await safeInvoke('query_all_orders', {
        sessionId: this.traderSessionId
      }) as ApiResponse<any[]>;

      if (result.success) {
        this.addLog(`查询到 ${result.data?.length || 0} 个未成交订单`, LogLevel.Info);
      } else {
        this.addLog(`查询订单失败: ${result.error}`, LogLevel.Error);
      }

      return result;
    } catch (error) {
      this.addLog(`查询订单异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  async queryInstruments(retryCount: number = 0): Promise<ApiResponse<InstrumentInfo[]>> {
    if (!this.traderSessionId) {
      const error = '请先创建交易API';
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    // 检查登录状态
    if (this.traderStatus !== 'login_success') {
      const error = `交易API未登录，当前状态: ${this.traderStatus}`;
      this.addLog(error, LogLevel.Error);
      return { success: false, error };
    }

    try {
      this.addLog(`查询合约信息 ${retryCount > 0 ? `(重试 ${retryCount}/3)` : ''}`, LogLevel.Info);

      // 添加超时控制
      const timeoutPromise = new Promise<ApiResponse<InstrumentInfo[]>>((_, reject) => {
        setTimeout(() => {
          reject(new Error('查询合约超时（45秒），请检查网络连接和CTP服务状态'));
        }, 45000); // 45秒超时
      });

      const queryPromise = safeInvoke('query_instruments', {
        sessionId: this.traderSessionId
      }) as Promise<ApiResponse<InstrumentInfo[]>>;

      const result = await Promise.race([queryPromise, timeoutPromise]);

      if (result.success) {
        const instruments = result.data || [];
        this.addLog(`合约查询成功，共 ${instruments.length} 个合约`, LogLevel.Info);

        // 记录主要合约信息
        instruments.slice(0, 5).forEach(inst => {
          this.addLog(`合约: ${inst.instrument_id} ${inst.instrument_name}`, LogLevel.Info);
        });

        if (instruments.length > 5) {
          this.addLog(`... 还有 ${instruments.length - 5} 个合约`, LogLevel.Info);
        }
      } else {
        this.addLog(`合约查询失败: ${result.error}`, LogLevel.Error, result);

        // 如果是超时错误且重试次数小于3，则自动重试
        if (result.error?.includes('超时') && retryCount < 3) {
          this.addLog(`准备重试查询合约 (${retryCount + 1}/3)`, LogLevel.Warning);
          await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒后重试
          return this.queryInstruments(retryCount + 1);
        }

        // 如果查询失败，提供诊断信息
        try {
          const diagnostic = await this.checkConnectionStatus();
          if (diagnostic.success && diagnostic.data) {
            const suggestions = diagnostic.data.suggestions || [];
            suggestions.forEach((suggestion: string) => {
              this.addLog(`建议: ${suggestion}`, LogLevel.Warning);
            });
          }
        } catch (diagError) {
          this.addLog(`诊断检查失败: ${diagError}`, LogLevel.Warning);
        }
      }

      return result;
    } catch (error) {
      const errorMessage = String(error);
      this.addLog(`合约查询异常: ${errorMessage}`, LogLevel.Error, error);

      // 如果是超时错误且重试次数小于3，则自动重试
      if (errorMessage.includes('超时') && retryCount < 3) {
        this.addLog(`准备重试查询合约 (${retryCount + 1}/3)`, LogLevel.Warning);
        await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒后重试
        return this.queryInstruments(retryCount + 1);
      }

      return {
        success: false,
        error: errorMessage
      };
    }
  }

  async checkConnectionStatus(): Promise<ApiResponse<any>> {
    if (!this.traderSessionId) {
      return {
        success: false,
        error: '请先创建交易API'
      };
    }

    try {
      const result = await safeInvoke('check_ctp_connection_status', {
        sessionId: this.traderSessionId
      }) as ApiResponse<any>;

      if (result.success && result.data) {
        this.addLog('连接状态检查完成', LogLevel.Info);

        const status = result.data;
        this.addLog(`交易API存在: ${status.trader_api_exists}`, LogLevel.Info);
        this.addLog(`登录状态: ${status.login_status}`, LogLevel.Info);
        this.addLog(`配置存在: ${status.config_exists}`, LogLevel.Info);

        if (status.suggestions && status.suggestions.length > 0) {
          this.addLog('诊断建议:', LogLevel.Warning);
          status.suggestions.forEach((suggestion: string) => {
            this.addLog(`- ${suggestion}`, LogLevel.Warning);
          });
        }
      }

      return result;
    } catch (error) {
      this.addLog(`连接状态检查异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 网络连接诊断方法
  async diagnoseNetworkConnection(): Promise<ApiResponse<any>> {
    this.addLog('开始网络连接诊断', LogLevel.Info);

    const diagnosticResults = {
      networkOnline: navigator.onLine,
      traderStatus: this.traderStatus,
      sessionExists: !!this.traderSessionId,
      timestamp: new Date().toISOString(),
      suggestions: [] as string[]
    };

    // 检查基本网络状态
    if (!diagnosticResults.networkOnline) {
      diagnosticResults.suggestions.push('网络连接异常，请检查网络设置');
    }

    // 检查会话状态
    if (!diagnosticResults.sessionExists) {
      diagnosticResults.suggestions.push('交易会话不存在，请重新创建交易API');
    }

    // 检查登录状态
    if (diagnosticResults.traderStatus !== 'login_success') {
      diagnosticResults.suggestions.push(`交易状态异常(${diagnosticResults.traderStatus})，请重新登录`);
    }

    // 尝试连接状态检查
    try {
      const connectionCheck = await this.checkConnectionStatus();
      if (!connectionCheck.success) {
        diagnosticResults.suggestions.push('CTP连接状态检查失败，可能是服务器问题');
      }
    } catch (error) {
      diagnosticResults.suggestions.push(`连接检查异常: ${error}`);
    }

    this.addLog(`网络诊断完成，发现 ${diagnosticResults.suggestions.length} 个问题`,
      diagnosticResults.suggestions.length > 0 ? LogLevel.Warning : LogLevel.Info);

    return {
      success: true,
      data: diagnosticResults
    };
  }

  async forceSetTraderLoginStatus(status: boolean): Promise<ApiResponse<string>> {
    if (!this.traderSessionId) {
      return {
        success: false,
        error: '请先创建交易API'
      };
    }

    try {
      const result = await safeInvoke('force_set_trader_login_status', {
        sessionId: this.traderSessionId,
        status
      }) as ApiResponse<string>;

      if (result.success) {
        this.addLog(`强制设置登录状态: ${status ? '已登录' : '未登录'}`, LogLevel.Info);
        // 更新本地状态
        if (status) {
          this.traderStatus = 'login_success' as ConnectionStatus;
        } else {
          this.traderStatus = 'disconnected' as ConnectionStatus;
        }
        this.emit('trader_status_change', this.traderStatus);
      } else {
        this.addLog(`设置登录状态失败: ${result.error}`, LogLevel.Error);
      }

      return result;
    } catch (error) {
      this.addLog(`设置登录状态异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 结算确认
  async settlementInfoConfirm(): Promise<ApiResponse<string>> {
    if (!this.traderSessionId) {
      return {
        success: false,
        error: '请先创建交易API'
      };
    }

    try {
      this.addLog('开始结算确认...', LogLevel.Info);

      const result = await safeInvoke('settlement_info_confirm', {
        sessionId: this.traderSessionId
      }) as ApiResponse<string>;

      if (result.success) {
        this.addLog('结算确认成功', LogLevel.Info);
        this.addLog(`确认信息: ${result.data}`, LogLevel.Info);
      } else {
        this.addLog(`结算确认失败: ${result.error}`, LogLevel.Error, result);
      }

      return result;
    } catch (error) {
      this.addLog(`结算确认异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 检查结算确认状态
  async checkSettlementConfirmStatus(): Promise<ApiResponse<boolean>> {
    if (!this.traderSessionId) {
      return {
        success: false,
        error: '请先创建交易API'
      };
    }

    try {
      const result = await safeInvoke('check_settlement_confirm_status', {
        sessionId: this.traderSessionId
      }) as ApiResponse<boolean>;

      if (result.success) {
        const status = result.data ? '已确认' : '未确认';
        this.addLog(`结算确认状态: ${status}`, LogLevel.Info);
      } else {
        this.addLog(`检查结算确认状态失败: ${result.error}`, LogLevel.Warning);
      }

      return result;
    } catch (error) {
      this.addLog(`检查结算确认状态异常: ${error}`, LogLevel.Error, error);
      return {
        success: false,
        error: String(error)
      };
    }
  }

  // 状态获取方法
  getMdStatus(): ConnectionStatus {
    return this.mdStatus;
  }

  getTraderStatus(): ConnectionStatus {
    return this.traderStatus;
  }

  getLogs(): LogEntry[] {
    return [...this.logs];
  }

  getMdSessionId(): string | null {
    return this.mdSessionId;
  }

  getTraderSessionId(): string | null {
    return this.traderSessionId;
  }

  // 获取有效的交易会话ID，如果当前会话无效则尝试从缓存恢复
  async getValidTraderSessionId(): Promise<string | null> {
    // 如果当前有会话ID，直接返回
    if (this.traderSessionId) {
      return this.traderSessionId;
    }

    // 尝试从缓存获取有效的会话ID
    const cachedSessionId = await sessionManager.getValidTraderSessionId();
    if (cachedSessionId) {
      this.traderSessionId = cachedSessionId;
      this.traderStatus = 'login_success' as ConnectionStatus;
      return cachedSessionId;
    }

    return null;
  }

  // 清理特定窗口的资源
  cleanupWindow(windowId: string) {

    // 清理该窗口的所有事件监听器
    this.windowEventListeners.forEach((eventMap, eventType) => {
      if (eventMap.has(windowId)) {
        eventMap.delete(windowId);
      }
    });
  }

  // 释放交易API
  async releaseTraderApi(): Promise<ApiResponse<string>> {
    if (!this.traderSessionId) {
      return {
        success: false,
        error: '没有活跃的交易API会话'
      };
    }

    try {
      this.addLog(`释放交易API: ${this.traderSessionId}`, LogLevel.Info);

      const result = await safeInvoke('release_trader_api', {
        sessionId: this.traderSessionId
      }) as ApiResponse<string>;

      if (result.success) {
        this.traderSessionId = null;
        this.traderStatus = 'disconnected' as ConnectionStatus;
        this.emit('trader_status_change', this.traderStatus);
        this.addLog('交易API已释放', LogLevel.Info);
        this.saveSessionToCache();
      } else {
        this.addLog(`释放交易API失败: ${result.error}`, LogLevel.Error, result);
      }

      return result;
    } catch (error) {
      const errorMessage = `释放交易API异常: ${error}`;
      this.addLog(errorMessage, LogLevel.Error, error);
      return {
        success: false,
        error: errorMessage
      };
    }
  }

  // 清理方法
  async cleanup() {

    // 收集需要清理缓存的会话ID
    const sessionIdsToCleanup: string[] = [];
    if (this.mdSessionId) {
      sessionIdsToCleanup.push(this.mdSessionId);
    }
    if (this.traderSessionId && this.traderSessionId !== this.mdSessionId) {
      sessionIdsToCleanup.push(this.traderSessionId);
    }

    // 释放交易API
    if (this.traderSessionId) {
      try {
        await this.releaseTraderApi();
      } catch (error) {
      }
    }

    // 释放行情API
    if (this.mdSessionId) {
      try {
        await this.releaseMdApi();
      } catch (error) {
      }
    }
    // 清理其他资源
    this.eventListeners.clear();
    this.windowEventListeners.clear();
    this.logs = [];
    this.mdSessionId = null;
    this.traderSessionId = null;
    this.mdStatus = 'disconnected' as ConnectionStatus;
    this.traderStatus = 'disconnected' as ConnectionStatus;
  }
}

// 创建单例实例
export const ctpService = CtpService.getInstance();
